<template>
  <!-- 告警管理 -->
  <div class="app-container alarm-vue table-flex-wrapper">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item>
        <selector type="sensorType" size="small" style="width: 160px" clearable placeholder="请选择传感器类型" v-model="queryParams.sensorType"></selector>
      </el-form-item>
      <el-form-item>
        <selector ref="levelSelector" type="alarmLevel" size="small" style="width: 160px" clearable placeholder="请选择告警等级"
          v-model="queryParams.alarmLevel"></selector>
      </el-form-item>
      <el-form-item>
        <selector type="alarmHandleState" size="small" style="width: 160px" clearable placeholder="请选择处理状态" v-model="queryParams.alarmState"></selector>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="dateRange" size="small" style="width: 220px;vertical-align:middle"
          value-format="yyyy-MM-dd" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryParams.deviceName" placeholder="模糊搜索设备名称" clearable size="small" style="width: 180px" />
      </el-form-item>
      <el-form-item class="alarm-QQbrowser-update">
        <el-button icon="el-icon-search" size="mini" @click="search" type="primary">搜索
        </el-button>
        <el-button size="mini" @click="AllClose" type="primary">一键关闭
        </el-button>
        <el-button :disabled="!ids.length" size="mini" @click="batchProcessing(1)" type="primary">批量处理
        </el-button>
        <el-button size="mini" @click="handleExport" type="primary" v-hasPermi="['system:post:export']">导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" size="mini" :data="operationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column prop="id" width="80" label="序号" align="center"></el-table-column>
      <el-table-column prop="content" width="150" label="监测内容" align="center"></el-table-column>
      <el-table-column prop="pointName" width="120" label="测点名称" align="center"></el-table-column>
      <el-table-column prop="type" width="90" label="传感器类型" align="center"></el-table-column>
      <el-table-column prop="equipmentName" width="120" label="设备名称" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column prop="testItem" label="监测项" align="center"></el-table-column>
      <el-table-column prop="site" min-width="160" label="坐标位置" align="center"></el-table-column>
      <el-table-column prop="workingStatus" width="80" label="工作状态" align="center">
        <template scope="scope">
          <span v-if="scope.row.workingStatus==1" style="color: #009900">正常</span>
          <span v-else-if="scope.row.workingStatus==2" style="color:rgb(182,182,182)">维护</span>
          <span v-else-if="scope.row.workingStatus==3" style="color:rgb(0,51,204)">已更换</span>
          <span v-else style="color:rgb(219,45,0)">离线</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="时间" min-width="150px" show-overflow-tooltip align="center" :formatter="handleTimeFarmat"></el-table-column>
      <el-table-column prop="grade" label="告警等级" align="center">
        <template scope="scope">
          <span v-if="scope.row.grade==1" style="color:rgb(52, 146, 252)">一级告警</span>
          <span v-else-if="scope.row.grade==2" style="color: rgb(255, 128, 0)">二级告警</span>
          <span v-else-if="scope.row.grade==3" style="color: rgb(255, 0, 0)">三级告警</span>
        </template>
      </el-table-column>
      <el-table-column label="阈值" align="center">
        <el-table-column width="70" align="center">
          <template slot="header">
            <el-tooltip content="发生山体滑坡可能性小,请密切观测" placement="top" effect="dark">
              <span style="color: #3492FC">一级
                <!--<i class="el-icon-question el-icon&#45;&#45;right"></i>-->
              </span>
            </el-tooltip>
          </template>
          <template scope="scope">
            <span style="color: #3492FC">{{ scope.row.thresholdValue.first }}</span>
          </template>
        </el-table-column>
        <el-table-column width="70" align="center">
          <template slot="header">
            <el-tooltip content="发生山体滑坡的可能性较大,请各岗位人员到岗待命" placement="top" effect="dark">
              <span style="color: #FF8000">二级</span>
            </el-tooltip>
          </template>
          <template scope="scope">
            <span style="color: #FF8000">{{ scope.row.thresholdValue.second }}</span>
          </template>
        </el-table-column>
        <el-table-column width="70" align="center">
          <template slot="header">
            <el-tooltip content="发生山体滑坡的可能性很大,及时采取人员介入,封锁相应道路" placement="top" effect="dark">
              <span style="color: #ff0000">三级</span>
            </el-tooltip>
          </template>
          <template scope="scope">
            <span style="color: #ff0000">{{ scope.row.thresholdValue.third }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column prop="alarmThreadhold" width="90" label="预警阈值" align="center">
        <template scope="scope">
          <span v-if="scope.row.alarmThreadhold>=scope.row.thresholdValue.third" style="color:rgb(255, 0, 0)">{{ scope.row.alarmThreadhold }}</span>
          <span v-else-if="scope.row.alarmThreadhold>=scope.row.thresholdValue.second" style="color: rgb(255, 128, 0)">{{ scope.row.alarmThreadhold }}</span>
          <span v-else style="color: rgb(52, 146, 252)">{{scope.row.alarmThreadhold }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="alarmValue" width="90" label="预警实测值" align="center">
        <template scope="scope">
          <span v-if="scope.row.alarmValue>=scope.row.thresholdValue.third" style="color:rgb(255, 0, 0)">{{ scope.row.alarmValue }}</span>
          <span v-else-if="scope.row.alarmValue>=scope.row.thresholdValue.second" style="color: rgb(255, 128, 0)">{{ scope.row.alarmValue }}</span>
          <span v-else style="color: rgb(52, 146, 252)">{{scope.row.alarmValue }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="disposalState" width="80" label="处置状态" align="center">
        <template scope="scope">
          <span v-if="scope.row.disposalState!=1" style="color:rgb(219,45,0)">{{ workTypeFormat(scope.row.disposalState) }}</span>
          <span v-else style="color: #009900">{{ workTypeFormat(scope.row.disposalState) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="140" prop="operation" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" class="btn" @click="handleUpdate(scope.row)" v-hasPermi="['system:role:edit']">处置
          </el-button>
          <el-button size="mini" class="btn white" type="primary" @click="deleteInfo(scope.row.id)" v-hasPermi="['slope:alarm:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 处置对话框 -->
    <div class="alarm-dialog">
      <el-dialog :title="dialogTitle" :visible.sync="openDialog" width="25%" v-loading="addAndUpdateLoading">
        <el-row class="info-detail-row">
          <el-col :xs="12" :sm="10" :md="8" :lg="6" :xl="4">监测内容：</el-col>
          <el-col :span="12">{{ showDataInfo.number }}</el-col>
        </el-row>
        <el-row class="info-detail-row">
          <el-col :xs="12" :sm="10" :md="8" :lg="6" :xl="4">设备名称：</el-col>
          <el-col :span="12">{{ showDataInfo.name }}</el-col>
        </el-row>
        <el-row class="info-detail-row">
          <el-col :xs="12" :sm="10" :md="8" :lg="6" :xl="4">告警等级：</el-col>
          <el-col :span="12">{{ showDataInfo.level }}</el-col>
        </el-row>
        <el-row class="info-detail-row">
          <el-col :xs="12" :sm="10" :md="8" :lg="6" :xl="4">告警值：</el-col>
          <el-col :span="12">{{ showDataInfo.value }}</el-col>
        </el-row>
        <el-row class="info-detail-row">
          <el-col :xs="12" :sm="10" :md="8" :lg="6" :xl="4">告警阈值：</el-col>
          <el-col :span="12">{{ showDataInfo.thresholdValue }}</el-col>
        </el-row>
        <el-row class="info-detail-row">
          <el-col :xs="12" :sm="10" :md="8" :lg="6" :xl="4">告警时间：</el-col>
          <el-col :span="12">{{ handleTimeFarmat(showDataInfo.createTime) }}</el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button @click="openDialog = false">取 消</el-button>
          <el-button type="primary" @click="handleDispose(2)">无需处置</el-button>
          <el-button type="primary" @click="handleDispose(1)">已解决</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import selector from "@/views/components/selector";
  import { listAlarm, changSelectedAlarmStatus, changeAlarmStatusById, exportAlarm, oneClickClose, deleteAlarm } from "@/api/page/alarm.js";
  import alarmScss from "./alarm.scss";

  export default {
    name: "equipment",
    components: {
      selector
    },
    data() {
      return {
        // 表格数据
        operationList: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          sensorType: undefined,
          alarmLevel: undefined,
          alarmState: undefined,
          deviceName: undefined
        },
        // 表单参数
        form: {},
        // 是否打开处置对话框
        openDialog: false,
        // 对话框标题
        dialogTitle: "",
        // 对话框展示框
        showDataInfo: {
          number: "",
          name: "",
          level: "",
          value: "",
          thresholdValue: {},
          createTime: ""
        },
        pickerOptions: {
          shortcuts: [{
              text: "最近一天",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近三天",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              }
            }
          ]
        },
        // 新增和修改时发送请求的遮罩层
        addAndUpdateLoading: false,
        // 导出加载框
        exportLoading: {
          lock: true,
          text: '导出文件较多，请耐心等候',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        },
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询告警列表 */
      getList() {
        let self = this;
        self.loading = true;
        listAlarm(this.addDateRange(self.queryParams, self.dateRange)).then(
          response => {
            let obj = response.rows;
            let result = [];
            obj.forEach(e => {
              let sensor = e.alarmSensor;
              let monitorItem = e.monitorItem;
              let json = {
                id: e.alarmId,
                content: sensor.monitorDetail,
                pointName: sensor.device.point.pointName,
                type: sensor.sensorType.typeName,
                equipmentName: sensor.device.deviceName,
                testItem: monitorItem.itemName, //侧项
                site: sensor.device.point.lon + " " + sensor.device.point.lat,
                workingStatus: sensor.device.state,
                createTime: e.alarmTime,
                grade: e.alarmLevel,
                thresholdValue: {
                  first: monitorItem.threshold1,
                  second: monitorItem.threshold2,
                  third: monitorItem.threshold3
                },
                alarmThreadhold: e.alarmThreadhold,
                disposalState: e.alarmState,
                alarmValue: e.alarmValue
              };
              result.push(json);
            });
            self.operationList = result;
            self.total = response.total;
            self.loading = false;
          }
        ).catch((error)=>{
          self.loading = false;
          console.log(error);
        });
      },

      /** 搜索 */
      search() {
        let self = this;
        this.queryParams.pageNum = 1;
        self.getList();
        console.log("搜索：", self.queryParams);
      },

      /** 一键关闭 */
      AllClose() {
        var self = this;
        this.$confirm("确认要一键关闭吗", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return oneClickClose();
          })
          .then(res => {
            if (res.code === 200) {
              self.msgSuccess("关闭成功");
              self.getList();
            } else {
              self.msgError(res.msg);
            }
          }).catch((msgError)=>{
          console.log(msgError);
        });
        },

      /* 处置 */
      handleDispose(state) {
        let self = this;
        self.addAndUpdateLoading = true;
        changeAlarmStatusById({ alarmId: this.showDataInfo.id, state }).then(res => {
          if (res.code === 200) {
            self.msgSuccess("操作成功");
            self.openDialog = false;
            self.getList();
          } else {
            self.msgError(res.msg);
          }
          self.addAndUpdateLoading = false;
        }).catch((error)=>{
          self.addAndUpdateLoading = false;
          console.log(error);
        });
      },

      /** 批量处置 */
      batchProcessing(state) {
        var self = this;
        this.$confirm("确认要批量处理吗", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            return changSelectedAlarmStatus({
              idArr: self.ids.join(","),
              state: state
            });
          })
          .then(res => {
            if (res.code === 200) {
              self.msgSuccess("处理成功");
              self.getList();
            } else {
              self.msgError(res.msg);
            }
          }).catch((msgError)=>{
            console.log(msgError);
          });
      },

      /** 导出按钮操作 */
      handleExport() {
        let self = this;
        const queryParams = self.queryParams;
        let loading = undefined;
        this.$confirm("是否确认导出所有数据?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(function() {
            loading = self.$loading(self.exportLoading);
            return exportAlarm(queryParams);
          })
          .then(response => {
            this.download(response.msg);
            loading.close();
          })
          .catch(function() {
            if (loading!=undefined) {
              loading.close();
            }
          });
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
      },

      /** 处理告警按钮 */
      handleUpdate(row) {
        let self = this;
        self.openDialog = true;
        self.dialogTitle = "告警处置";
        self.showDataInfo.id = row.id,
          self.showDataInfo.number = row.content,
          self.showDataInfo.name = row.pointName,
          self.showDataInfo.level = self.warningTypeFormat(row.grade),
          self.showDataInfo.value = row.alarmValue,
          self.showDataInfo.thresholdValue = row.thresholdValue.first + " / " + row.thresholdValue.second + " / " + row
          .thresholdValue.third,
          self.showDataInfo.createTime = row.createTime;
      },

      /**
       * 删除告警管理信息
       * @param id 告警管理id
       */
      deleteInfo(id) {
        let self = this;
        self.$confirm( "确认要删除该条信息吗?", "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          })
          .then(function() {
            deleteAlarm(id).then(res=>{
              if(res.code==200){
                self.msgSuccess(res.msg);
              }else{
                self.msgError(res.msg);
              }
            });
          })
          .then(() => {
            self.getList();
          })
          .catch(function() {
        });
      },

      // 查询的条件发生了改变
      handleQuery() {
        let self = this;
        console.log(self.queryParams);
      },
      //告警级别
      warningTypeFormat(val) {
        if (val == 1) {
          return "一级告警";
        } else if (val == 2) {
          return "二级告警";
        } else if (val == 3) {
          return "三级告警";
        }
      },
      //处置状态
      workTypeFormat(val) {
        if (val == 0) {
          return "未解决";
        } else if (val == 1) {
          return "已解决"
        } else if (val == 2) {
          return "无需处置"
        }
      },

      //时间格式处理
      handleTimeFarmat(val) {
        val = val.createTime == null ? val : val.createTime;
        return val.substring(0, 10) + " " + val.substring(11, 19);
      }

    }
  };
</script>
